<?php

namespace App\Util;

use App\Core\Exception\DefaultException;
use App\Lib\Util\QiniuUpload;
use App\Logic\Member\MemberItgLogService;
use App\Logic\Product\CooperationService;
use App\Logic\Product\ProductService;
use App\Logic\Purchase\PurchaseService;
use App\Logic\Shipping\ShippingService;
use App\Logic\Supplier\SupplierService;
use App\Model\DownloadCenter\DownloadCenterModel;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Config as ESConfig;
use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\Redis\Redis;


class DownloadHelper{

    /**
     * 异步下载到缓存数据
     */
    public function asyncDownloadCache($id,$cacheKey,$params): array
    {
        $this->getPageData($id,$cacheKey,$params);
        $redisConfig = ESConfig::getInstance()->getConf('REDIS');
        $redis = new Redis(new RedisConfig([
            'host'      => $redisConfig['host'],
            'port'      => $redisConfig['port'],
            'auth'      => $redisConfig['auth'],
            'serialize' => $redisConfig['serialize']
        ]));

        $result = (array)$redis->hGetAll($cacheKey.$id);
        foreach ($result as &$value){
            $value = json_decode($value,true);
        }
        ksort($result);
        return $result;
    }

    /**
     * 获取分页数据
     */
    public function getPageData($id,$cacheKey,$params){
        $data = [];
        switch ($cacheKey){
            case 'download:orderShippingLists:' ://发货单
                $service = new ShippingService();
                $result  = $service->getDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:supplierLists:' ://供应商
                $service = new SupplierService();
                $result  = $service->getDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:sortingSkuLists:' ://上下架SKU
                $service = new ProductService();
                $result  = $service->getSortingSkuDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:sortingSpuLists:' ://上下架SPU
                $service = new ProductService();
                $result  = $service->getSortingSpuDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:cooperationSkuLists:' ://自营SKU
                $service = new CooperationService();
                $result  = $service->getSkuDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:cooperationSpuLists:' ://自营SPU
                $service = new CooperationService();
                $result  = $service->getSpuDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:PackageSkuLists:' ://整包SKU
                $service = new ProductService();
                $result  = $service->getPackageSkuDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:purchaseLists:' ://采购单
                $service = new PurchaseService();
                $result  = $service->getDownloadData($params);
                $data    = $result->getData();
                break;
            case 'download:itgLogLists:' ://积分记录
                $service = new MemberItgLogService();
                $result = $service->getDetailsList($params, $params['page'] ?? 1, $params['pageSize'] ?? 100);
                $data = $result->getData();
                break;
            default:
                break;
        }

        $list       = $data['list'] ?: [];
        $pagination = $data['pagination'] ?: [];
        $totalCount = $pagination['total_count'] ?: 1;
        $pageSize   = $pagination['page_size'] ?: 100;
        $totalPage  = ceil($totalCount/$pageSize);

        //实例化
        $redisConfig = ESConfig::getInstance()->getConf('REDIS');
        $redis = new Redis(new RedisConfig([
            'host'      => $redisConfig['host'],
            'port'      => $redisConfig['port'],
            'auth'      => $redisConfig['auth'],
            'serialize' => $redisConfig['serialize']
        ]));

        foreach ($list as $value){
            $redis->hset($cacheKey.$id, $value['id'],json_encode($value));
        }
        $redis->expire($cacheKey.$id,3*3600);

        if($params['page']<$totalPage&&$params['page']<500){
            $params['page'] = $params['page']+1;
            $this->getPageData($id,$cacheKey,$params);
        }
        return $totalPage;
    }

    /**
     * 上传Excel到七牛云
     * @throws DefaultException
     */
    public function upload2Qiniu($id,$resultData){
        $qiniuConfig = Config::getInstance()->getConf('QINIUCONFIG');
        $upload = new QiniuUpload($qiniuConfig);
        $xls    = $upload->upload($resultData['filename'],md5($resultData['filename']).".qiniu.xls");

        if(!empty($xls)){
            $downloadCenter = DownloadCenterModel::getOne(['id' => $id], true);
            $updateData       = [
                'finished_at' => date('Y-m-d H:i:s', time()),
                'qiniu_url'   => $xls?:'',
                'status'      => 2,
            ];

            $model  = new DownloadCenterModel();
            $result = $model->where(['id'=>$id])->update($updateData);
            unlink($downloadCenter['filename']);//删除文件
            if(empty($result)){
                throw new DefaultException('上传七牛云失败！');
            }
        }
    }
    
}